package com.compass.mobile.ui.activity

import LogUtil
import UserInfoManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.View.OnKeyListener
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.leanback.widget.OnChildViewHolderSelectedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.ActivityRecommendDoctorBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.textChangeFlow
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.Dictionaries
import com.compass.mobile.models.Doctor
import com.compass.mobile.presenters.DoctorPresenter
import com.compass.mobile.ui.viewModel.DoctorViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import toBeanOrNull
import toJson

/**
 * Description： 推荐医生
 * Date:2024/6/29 14:10
 */
class RecommendedDoctorActivity : BaseVBActivity<ActivityRecommendDoctorBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, RecommendedDoctorActivity::class.java)
            context.startActivity(intent)
        }
    }

    private var keyWords: String? = null
    private val doctorViewModel: DoctorViewModel by viewModels()
    private var doctors: MutableList<Doctor> = mutableListOf()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var isFirst = true

    override fun initView(savedInstanceState: Bundle?) {
        initSpecialColumn()
        mBinding.edtKeyWords.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击了搜索按钮后，需要隐藏软键盘
                keyWords = mBinding.edtKeyWords.text.toString().trim()
                getDoctor()

            }
            false
        }


        mBinding.edtKeyWords.textChangeFlow()
            .distinctUntilChanged()
            .debounce(500)
            .flowOn(Dispatchers.IO)
            .onEach {
                //这里走查询接口
                keyWords = mBinding.edtKeyWords.text.toString().trim()
                getDoctor()
            }
            .launchIn(lifecycleScope)

    }


    private fun getDoctor() {
        if (keyWords.isNullOrEmpty() && !isFirst) {
            setDoctor(UserInfoManager.getAllDoctor()?.toBeanOrNull<MutableList<Doctor>>())
        } else {
            doctorViewModel.searchDoctors(keyWords)
        }
    }

    override fun initData() {
        showLoading()
        getDoctor()
        doctorViewModel.doctorsLiveData.observe(this) {
            dismissLoading()
            arrayObjectAdapter.clear()
            if (isFirst) {
                isFirst = false //第一缓存全部医生数据
                UserInfoManager.saveAllDoctorType(it?.toJson())
            }
            setDoctor(it)

        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        LogUtil.d("action===${event?.action}  ----isMoveTop===$isMoveTop")
        if (event?.action == KeyEvent.ACTION_UP && isMoveTop) {
            mBinding.edtKeyWords.requestFocus()
        }
        return super.onKeyDown(keyCode, event)
    }
    private fun setDoctor(list: MutableList<Doctor>?) {

        if (list.isNullOrEmpty()) {
            mBinding.emptyView.visible()
        } else {
            mBinding.emptyView.gone()
            doctors = list
            arrayObjectAdapter.addAll(0, doctors)
        }
    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = doctors[position]


            item.department?.let {
                DoctorHomePageActivity.start(this@RecommendedDoctorActivity, item.id, it)
            }


        }
    }


    @SuppressLint("RestrictedApi")
    fun initSpecialColumn() {
        mBinding.caseItem.setNumColumns(2)
        mBinding.caseItem.horizontalSpacing = dpToPx(10)
        mBinding.caseItem.verticalSpacing = dpToPx(10)
        val departmentIntroductionPresenter = DoctorPresenter("2")
        arrayObjectAdapter = ArrayObjectAdapter(departmentIntroductionPresenter)
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, onItemClickListener
        )
        mBinding.caseItem?.setOnChildViewHolderSelectedListener(onChildViewHolderSelectedListener)
        mBinding.caseItem.setAdapter(itemBridgeAdapter)
        mBinding.caseItem.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, doctors)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
        mBinding.caseItem.requestFocus()
    }

    private var isMoveTop = true
    private val onChildViewHolderSelectedListener: OnChildViewHolderSelectedListener = object :
        OnChildViewHolderSelectedListener() {
        override fun onChildViewHolderSelected(
            parent: RecyclerView?,
            child: RecyclerView.ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            if (position < 3) {
                isMoveTop = true
            } else {
                isMoveTop = false
            }
        }
    }


}